package com.topisv.tms.web.phone;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.BackupTask;
import com.topisv.tms.entity.BackupTaskSku;
import com.topisv.tms.entity.ShippedBox;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.work.WorkTaskItem;
import com.topisv.tms.service.BackupTaskService;
import com.topisv.tms.service.BackupTaskSkuService;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.shipped.ShippedBoxService;
import com.topisv.tms.service.work.WorkTaskItemService;
import com.topisv.tms.utils.enums.StatusEnums;
//import com.topisv.tms.utils.http.SynchroShippedBatchQueue;

/**
 * 集发拣货装箱
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/phone")
public class FocusPhoneController {

	private static final Logger log = LoggerFactory.getLogger(FocusPhoneController.class);
	@Autowired
	private BackupTaskService backupTaskService;
	@Autowired
	private WorkTaskItemService workTaskItemService;

	@Autowired
	private ShippedBoxService shippedBoxService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private BackupTaskSkuService backupTaskSkuService;

	
	/**
	 * 
	 * @param jobuuid
	 * @param pickType 拣货任务类型(picking)先拣货再装箱,(pickBox)边拣货边装箱
	 * @param response
	 */
	@RequestMapping(value = "ajaxPickBackupList")
	public void ajaxPickTaskList(@RequestParam(value = "jobuuid") String jobuuid,@RequestParam(value = "pickType") String pickType,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		List<BackupTask> taskList =null;
		try {
			json = new JSONObject();
			out = response.getWriter();
		    User curUser=this.accountService.findUserByJobuuid(jobuuid);
            if(curUser==null){
            	json.put("status", "0"); 
    			json.put("content", "该用户不存在"); 
    			out.print(json.toString());
    			return;
            }
            if(!("picking".equals(pickType)||"pickBox".equals(pickType))){
            	json.put("status", "0"); 
    			json.put("content", "批次类型不正确"); 
    			out.print(json.toString());
    			return;
            }
            Map<String, Object> maps=new HashMap<String, Object>();
            maps.put("warehouseCode", curUser.getAreagroups());
       	    maps.put("status", "pending");
       	    maps.put("jobuuid", "pending:"+jobuuid);
       	    maps.put("pickType", "pending:"+pickType);
            if(StatusEnums.user_type_customer.getStatus().equals(curUser.getUserType())){//商家用户
                maps.put("customers", curUser.getCustomerCode());
			}else if(StatusEnums.user_type_paiu.getStatus().equals(curUser.getUserType())){//派友用户
	            maps.put("customers", curUser.getCustomers());
			}
            taskList=this.backupTaskService.findBackupTaskStatus(maps);
            if(taskList==null||taskList.isEmpty()){
            	json.put("status", "0"); //查询成功
     			json.put("content", "没有任务"); //任务列表
            	
            }else{
            	json.put("status", "1"); //查询成功
     			json.put("content", taskList); //任务列表
            }
		   
			
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", "服务器异常");
			log.error("error",e);
		}
		out.print(json.toString());
		log.info("ajaxPickBackupList接口返回值:"+json.toString());
	}
	
	/**
	 * 
	 * @param pickType 边拣货再装箱(pickBox),先拣货再装箱(picking)
	 * @param taskCode
	 * @param jobuuid
	 * @param response
	 */
	@RequestMapping(value = "ajaxPickBackupDetail")
	public void ajaxPickTaskDetail(@RequestParam(value = "pickType") String pickType,@RequestParam(value = "backupTaskCode") String taskCode,@RequestParam(value = "jobuuid") String jobuuid,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			if(!("picking".equals(pickType)||"pickBox".equals(pickType))){
            	json.put("status", "0"); 
    			json.put("content", "批次类型不正确"); 
    			out.print(json.toString());
    			return;
            }
			//任务信息
			BackupTask task=this.backupTaskService.setJobuuid(taskCode, jobuuid,pickType);
			if(task==null){//表示该任务已经有人领取
				json.put("status", "0");
				json.put("content", "该任务已经领取");
				out.print(json.toString());
				return;
			}
			//装箱完毕
			if("finish".equals(task.getStatus())){
				json.put("status", "0");
				json.put("content", "该任务已经装箱完毕");
				out.print(json.toString());
				return;
			}
			
			//拣货完毕还未装箱,不能拣货需要调用装箱按钮
			if("finish".equals(task.getPickStatus())&&"pending".equals(task.getStatus())){
				json.put("status", "2");
				json.put("content", "该任务已经拣货完毕");
				out.print(json.toString());
				return;
			}
			
			//开始拣货
			List<WorkTaskItem> workTaskItemList=this.workTaskItemService.loadByTaskCode(taskCode);
			if(!workTaskItemList.isEmpty()){
				int i=0;
				int length=workTaskItemList.size();
				for(i=0;i<length;i++){
					if("unpicked".equals(workTaskItemList.get(i).getPickStatus())||"picking".equals(workTaskItemList.get(i).getPickStatus())){
						WorkTaskItem wti=workTaskItemList.get(i);
						json.put("status", "1"); 
						json.put("task", task);
						json.put("content", wti); //下一个拣货信息
						break;
					}
				}			
				
			}else{
				json.put("status", "0");
				json.put("content", "数据有误");
			}
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", "服务器异常");
			log.error("error",e);
		}
		out.print(json.toString());
		log.info("ajaxPickBackupDetail接口拣货返回值:"+json.toString());
	}
	
	/**
	 * 
	 * @param pickType 先拣货再装箱(pickBox),边拣货再装箱(picking)
	 * @param taskItemId
	 * @param sku
	 * @param response
	 */
	@RequestMapping(value = "ajaxBackupPick")
	public void ajaxPick(@RequestParam(value = "pickType") String pickType,@RequestParam(value = "taskItemId") Long taskItemId,String sku, HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			if(!("picking".equals(pickType)||"pickBox".equals(pickType))){
            	json.put("status", "0"); 
    			json.put("content", "批次类型不正确"); 
    			out.print(json.toString());
    			return;
            }
			//拣货
			String msg=this.backupTaskService.pick(taskItemId,sku,pickType);
			WorkTaskItem workTaskItem=workTaskItemService.findOne(taskItemId);
			BackupTask backupTask=this.backupTaskService.findByBackupTaskCode(workTaskItem.getTaskCode());
			json.put("task", backupTask); 
			if("finished".equals(msg)){
				json.put("status", "0"); 
				json.put("content", "当前拣货项已经完成"); 
			}else if("finishing".equals(msg)){
				//进行下一项拣货
				int rankno=workTaskItem.getRankno()+1;
				workTaskItem=workTaskItemService.findByTaskCodeAndRankno(workTaskItem.getTaskCode(), rankno);
				while("picked".equals(workTaskItem.getPickStatus())){
					rankno++;
					workTaskItem=workTaskItemService.findByTaskCodeAndRankno(workTaskItem.getTaskCode(), rankno);
				}
				if("picked".equals(workTaskItem.getPickStatus())){
					json.put("status", "0"); 
					json.put("content", "数据有误"); 
				}else{
					json.put("status", "1"); 
					json.put("content", workTaskItem); //下一个拣货信息
				}
				
			}else if("task_finishing".equals(msg)){
				json.put("status", "2"); 
				json.put("content", "该拣货任务已经完成"); 
			}else if("task_finished".equals(msg)){
				json.put("status", "2"); 
				json.put("content", "该拣货任务已经完成"); 
			}else if("error".equals(msg)){
				json.put("status", "0"); 
				json.put("content", "验证错误"); 
			}else{
				json.put("status", "1"); 
				json.put("content", workTaskItem); //下一个拣货信息
			}
		  
			
		} catch (Exception e) {
			json.put("status","0");
			json.put("content","服务器异常");
			log.error("error",e);
		}
		out.print(json.toString());
		log.info("ajaxBackupPick拣货接口返回值："+json.toString());
	}
	
	/**
	 * 商品封箱子
	 * @param backupTaskCode
	 * @param boxCode
	 * @param response
	 */
	@RequestMapping(value = "ajaxBackupCreateBox")
	public void ajaxPick(@RequestParam(value = "pickType") String pickType,@RequestParam(value="backupTaskCode") String backupTaskCode,@RequestParam(value="boxCode") String boxCode, HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		ShippedBox shippedBox=null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			shippedBox=this.shippedBoxService.findByBoxCode(boxCode);
			if(shippedBox!=null){
				json.put("status", 0);
				json.put("content", "该箱子编码已经存在");
				out.print(json.toString());
				return;
			}
		    //装箱
			if("pickBox".equals(pickType)){
				shippedBox=backupTaskService.excuteShippedBox(backupTaskCode, boxCode);
			}else if("picking".equals(pickType)){//先拣货再装箱的封箱方式
				shippedBox=shippedBoxService.excuteShippedBox(backupTaskCode, boxCode);
			}
			if(shippedBox==null){
				json.put("content", "请先扫描商品");
				json.put("status", 0);
				out.print(json.toString());
				return;
			}
			BackupTask task=this.backupTaskService.findByBackupTaskCode(backupTaskCode);
			json.put("content", shippedBox);
			json.put("status", 1);
			json.put("task", task);//使用status判断当前拣货任务是否处于出库批次推送状态
			if("finish".equals(task.getStatus())){
				//SynchroShippedBatchQueue.putSendBatchQueue(backupTaskCode);//自动推送出库批次
//				SynchroShippedBatchQueue.putSendMessageQueue("createBatch"+StatusEnums.split.getStatus()+backupTaskCode);
			}
		} catch (Exception e) {
			
			json.put("status", 0);
			json.put("content", "服务器异常");
			log.error("error",e);
		}
		out.print(json.toString());
		log.info("ajaxBackupCreateBox封箱接口返回值："+json.toString());
	}
	
	/**
	 * 先拣货再装箱商品装箱
	 * 
	 * @param backupTaskCode
	 * @param skuId
	 * @param response
	 */
	@RequestMapping(value = "ajaxCheckBackupTaskSkus")
	public void ajaxCheckBackupTaskSkus(
			@RequestParam(value = "backupTaskCode") String backupTaskCode,
			@RequestParam(value = "skuId") String skuId,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			BackupTaskSku backupTaskSku = backupTaskSkuService.skuEnchase(backupTaskCode, skuId);
			if (backupTaskSku == null) {
				json.put("status", "0");
				backupTaskSku = backupTaskSkuService.findByBackupTaskCodeAndSkuId(backupTaskCode, skuId);
				if (backupTaskSku == null) {
					json.put("content", "商品装箱扫描失败");
				} else {
					json.put("content", "商品装箱扫描失败");
				}
				out.print(json.toString());
				return;
			}
			BackupTask backupTask = backupTaskService.findByBackupTaskCode(backupTaskCode);
			List<BackupTaskSku> backupTaskSkus= backupTaskSkuService.findByBackupTaskCodeAndStatus(backupTaskCode, "pending");
			if(backupTaskSkus.isEmpty()){
				json.put("status", "2");
			}else{
				json.put("status", "1");
			}
			json.put("content", "商品装箱扫描成功");
			json.put("task", backupTask);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content","服务器异常");
			out.print(json.toString());
			
		}
	}

}
